import Vue from 'vue'
import axios from 'axios'
import store from '@/store'
import notification from 'ant-design-vue/es/notification'
import {
  VueAxios
} from './axios'
import {
  ACCESS_TOKEN
} from '@/store/mutation-types'
import qs from 'qs'

// 创建 axios 实例
const service = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL, // api base_url
  // headers: { 'Content-Type': 'application/json;charset=utf-8' }, // 即将被发送的自定义请求头
  withCredentials: true // 表示跨域请求时是否需要使用凭证
  // timeout: 10000 // 请求超时时间
})
// 跨域请求，允许保存cookie
axios.defaults.withCredentials = true
const err = error => {
  notification.error({
    message: '系统提示',
    description: '系统异常请联系管理员'
  })
  /* if (error.response) {
    const data = error.response.data
    const token = Vue.ls.get(ACCESS_TOKEN)
    if (error.response.status === 405) {
      notification.error({
        message: '系统提示',
        description: data.msg
      })
    } else if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
       notification.error({
        message: '当前用户未登录',
        description: '重新登录'
      })
      if (token) {
        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            window.location.reload()
          }, 1500)
        })
      }
    } else {
      notification.error({
        message: '系统提示',
        description: data.msg == null || data.msg === '' ? '系统异常' : data.msg
      })
    }
  } */
  return Promise.reject(error)
}

// request interceptor
service.interceptors.request.use(config => {
  const token = Vue.ls.get(ACCESS_TOKEN)
  if (token) {
    config.headers['Authorization'] = 'Bearer ' + token // 让每个请求携带自定义 token 请根据实际情况自行修改
  }
  return config
}, err)

// response interceptor
service.interceptors.response.use(response => {
  const data = response.data
  if (data.access_token != null || data.code === 200) {
    return data
  }
  const token = Vue.ls.get(ACCESS_TOKEN)
  // 判断当前帐号和密码是否正确
  if (data.code === 405 || data.code === 401) {
    notification.error({
      message: '系统提示',
      description: data.msg
    })
    if (data.code === 401 && token != null && token !== '') {
      /* Vue.ls.remove(ACCESS_TOKEN)
      window.location.reload() */
      store.dispatch('Logout').then(() => {
        window.location.reload()
      })
    }
  } else {
    notification.error({
      message: '系统提示',
      description: data.msg == null || data.msg === '' ? '系统异常' : data.msg
    })
  }
  return Promise.reject(response)
}, err)

const installer = {
  vm: {},
  install(Vue) {
    Vue.use(VueAxios, service)
  }
}

export {
  installer as VueAxios, service as axios, qs
}
